package cn.mulanbay.admin.api.web.common;

import cn.mulanbay.api.system.bean.RemoteSystemLog;
import cn.mulanbay.api.system.service.RemoteLogService;
import cn.mulanbay.business.handler.ThreadPoolHandler;
import cn.mulanbay.common.config.CacheKey;
import cn.mulanbay.common.util.IPAddressUtil;
import cn.mulanbay.common.util.StringUtil;
import cn.mulanbay.web.common.ApiExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 异常处理类
 *
 * @author fenghong
 */
@ControllerAdvice
public class AdminApiExceptionHandler extends ApiExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(AdminApiExceptionHandler.class);

    @Value("${system.need.systemLog}")
    boolean needSystemLog;

    @Autowired
    RemoteLogService remoteLogService;

    @Autowired
    ThreadPoolHandler threadPoolHandler;

    @Override
    protected boolean doSystemLog() {
        return needSystemLog;
    }

    @Override
    protected void addSystemLog(HttpServletRequest request, Class exceptionClass, String title, String msg, int errorCode) {
        try {
            //userId由网关设置
            String us = request.getHeader(CacheKey.DETAILS_USER_ID);
            Long userId = null ;
            if(StringUtil.isNotEmpty(us)){
                userId = Long.valueOf(us);
            }
            RemoteSystemLog log = new RemoteSystemLog();
            log.setUserId(userId);
            log.setErrorCode(errorCode);
            log.setTitle(title);
            log.setContent(msg);
            log.setUrlAddress(request.getRequestURI());
            log.setMethod(request.getMethod());
            log.setOccurTime(LocalDateTime.now());
            log.setIpAddress(IPAddressUtil.getIpAddress(request));
            log.setExceptionClassName(exceptionClass.getName());
            threadPoolHandler.pushThread(() -> {
                remoteLogService.addSystemLog(log);
            });
            logger.error("异常exceptionClass="+exceptionClass);
        } catch (Exception e) {
            logger.error("添加系统日志异常", e);
        }
    }

}
